<?php

namespace island\models;

use Yii;
use yii\data\Pagination;
use Exception;
/**
 * This is the model class for table "t_spu".
 *
 * @property string $SpuId
 * @property string $SpuName
 * @property string $SpuVector
 * @property integer $SpuPrice
 * @property string $ImgUrl
 * @property integer $ReferencePrice
 * @property string $OnDate
 * @property string $OffDate
 * @property string $UnsuitedPeople
 * @property string $SuitedPeople
 * @property integer $SpuStatus
 * @property integer $CategoryId
 * @property integer $CategoryIdSub
 * @property integer $CategoryIdTre
 * @property string $SpuAttribute
 * @property string $Reserv
 * @property string $WorkerId
 * @property integer $LimitBuy
 * @property integer $SpuType
 * @property integer $Duration
 * @property string $Procedure
 */
class TSpu extends \yii\db\ActiveRecord
{
    //产品详情是图片
    const DETAIL_TYPE_IMG = 0;
    //产品详情是文字
    const DETAIL_TYPE_TEXT = 1;

    // Spu的类型，1 - 普通商品   2 - 服务型商品
    const SPU_TYPE_RETAIL = 1;
    const SPU_TYPE_SERVICE = 2;
    const SPU_TYPE_PACKAGE = 3;

    public static function getValidSpuType($spuType, $defaultSpuType = self::SPU_TYPE_RETAIL)
    {
        if (in_array(
            $spuType,
            [
                self::SPU_TYPE_RETAIL,
                self::SPU_TYPE_SERVICE,
                self::SPU_TYPE_PACKAGE,
            ]
        )) {
            return $spuType;
        }

        return $defaultSpuType;
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 't_spu';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['SpuId', 'SpuName', 'SpuVector'], 'required'],
            [['SpuPrice', 'ReferencePrice', 'SpuStatus', 'CategoryId', 'CategoryIdSub', 'CategoryIdTre', 'LimitBuy', 'SpuType', 'Duration'], 'integer'],
            [['OnDate', 'OffDate'], 'safe'],
            [['SpuId', 'UnsuitedPeople', 'SuitedPeople', 'WorkerId'], 'string', 'max' => 40],
            [['SpuName', 'SpuAttribute', 'Reserv'], 'string', 'max' => 1024],
            [['SpuVector'], 'string', 'max' => 12000],
            [['ImgUrl', 'Procedure'], 'string', 'max' => 2048],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'SpuId' => '商品ID',
            'SpuName' => '商品名称',
            'SpuVector' => '商品属性维度及可选值',
            'SpuPrice' => '商品价格',
            'ImgUrl' => '图片url地址',
            'ReferencePrice' => '参考价格',
            'OnDate' => '入库时间，也即是创建时间',
            'OffDate' => '下架时间',
            'UnsuitedPeople' => '禁用人群',
            'SuitedPeople' => '适宜人群',
            'SpuStatus' => '商品状态 0 有效  100 无效',
            'CategoryId' => '商品一级类目id',
            'CategoryIdSub' => '商品二级类目id',
            'CategoryIdTre' => '商品三级类目id',
            'SpuAttribute' => '商品属性表',
            'Reserv' => '备注',
            'WorkerId' => '工作人员id',
            'LimitBuy' => '限制购买数量,0为不限制',
            'SpuType' => '默认是1普通商品   2是服务型商品',
            'Duration' => '服务时长',
            'Procedure' => '技师的服务流程 json储存',
        ];
    }
    //获取单条spu
    public static function getSpu($spuid){
        return TSpu::findOne($spuid);
    }

    //获取商品列表 ,带分页信息
    public static function getSpuList($page,$count){
        $data = TSpu::find()->orderBy(' OnDate desc ');
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $count]);
        return $goodslist = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all();
    }

    /**
     * 通过关键字搜索商品
     * @param unknown $search 搜索内容
     * @param unknown $count  每页多少条
     * @param unknown $page   当前页数
     */
    public static function getSpuForSearch($search, $count, $page){
        if(is_numeric($search)){
            $data = TSpu::find()
                ->where("SpuId like :SpuId or SpuVector like :SpuVector")
                ->addParams([':SpuId'=>"%$search%"])
                ->addParams([':SpuVector'=>"%$search%"])
                ->orderBy(' SpuId asc ');
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $count]);
            $spu_list = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all();
            $spulist = [];
            foreach ($spu_list as $key => $spu){
                $spulist[$key]['spuid'] = $spu['SpuId'];
                $spulist[$key]['name'] = $spu['SpuName'];
                $spulist[$key]['timestamp'] = strtotime($spu['OnDate']);
                //获取分类的名称
                $categoryname = TCategory::getCategoryName($spu['CategoryId'], $spu['CategoryIdSub'], $spu['CategoryIdTre']);
                $spulist[$key]['category'] = $categoryname;
                //商品维度
                if($spu['SpuVector'] != ''){
                    $vector = TSpu::getVector($spu['SpuVector']);
                    $spulist[$key]['tag'] = $vector;
                }
            }
        }else{
            //商品名称搜索
            $data = TSpu::find()
                ->where("t_spu.SpuName like :SpuName or SpuId like :SpuId")
                ->addParams([':SpuName'=>"%$search%"])
                ->addParams([':SpuId'=>"%$search%"])
                ->orderBy(' SpuId asc ');
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $count]);
            $spu_list = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all();
            $spulist = [];
            foreach ($spu_list as $key => $spu){
                $spulist[$key]['spuid'] = $spu['SpuId'];
                $spulist[$key]['name'] = $spu['SpuName'];
                $spulist[$key]['timestamp'] = strtotime($spu['OnDate']);
                //获取分类的名称
                $categoryname = TCategory::getCategoryName($spu['CategoryId'], $spu['CategoryIdSub'], $spu['CategoryIdTre']);
                $spulist[$key]['category'] = $categoryname;
                //商品维度
                if($spu['SpuVector'] != ''){
                    $vector = TSpu::getVector($spu['SpuVector']);
                    $spulist[$key]['tag'] = $vector;
                }
            }
        }
        $pageall = ceil($data->count()/$count);
        $data = ['pages' => $pageall, 'page' => $page, 'list' => $spulist];
        return $data;
    }
    //获取商品分页信息
    public static function getPages($count){
        $data = TSpu::find()->orderBy(' OnDate desc ');
        return ceil($data->count()/$count);
    }

    //转化为商品维度
    public static function getVector($spuvector){
        $spuvector = json_decode($spuvector,true);
        $vector = [];
        foreach ($spuvector as $k=>$v){
            if(isset($v['color'])){
                $color = [];
                $color['name'] = 'color';
                $color['values'][] = $v['color'];
                $vector[] = $color;
            }
            if(isset($v['size'])){
                $size = [];
                $size['name'] = 'size';
                $size['values'][] = $v['size'];
                $vector[] = $size;
            }
            if(isset($v['function'])){
                $function = [];
                $function['name'] = 'function';
                $function['values'][] = $v['function'];
                $vector[] = $function;
            }
            if(isset($v['cup'])){
                $cup = [];
                $cup['name'] = 'cup';
                $cup['values'][] = $v['cup'];
                $vector[] = $cup;
            }
        }
        return $vector;
    }

    //校验数据
    public static function checkForm($params){
        if (!isset($params['spuid'])){
            return '商品ID不能为空';
        }
        if (!isset($params['name'])){
            return '商品名称不能为空';
        }
    }

    //增加商品
    public static function addSpu($params){
        try {
            if ($params['roles'] == 2) {
                return json_encode(['code' => 1, 'msg' => '您没有添加商品的权限']);
            }
            $spu = new TSpu();
            $spu->SpuId = $params['spuid'];
            $spu->SpuName = $params['name'];
            if (isset($params['category'])) {
                foreach ($params['category'] as $key => $category) {
                    if ($key == 0) {
                        $spu->CategoryId = $category['id'];
                        //商品分类属性
                        if (isset($params['tag'])) {
                            $spu->SpuAttribute = json_encode($params['tag']['selected'], JSON_UNESCAPED_UNICODE);
                        }
                    }
                    if ($key == 1) {
                        $spu->CategoryIdSub = $category['id'];
                    }
                    if ($key == 2) {
                        $spu->CategoryIdTre = $category['id'];
                    }
                }
            } else {
                $spu->CategoryId = 0;
                $spu->CategoryIdSub = 0;
                $spu->CategoryIdTre = 0;
                $spu->SpuAttribute = json_encode([]);
            }
            //启动事务
            $dbTrans = Yii::$app->db->beginTransaction();
            try {
                //库存列表添加
                if (isset($params['skuList'])) {
                    $spuid = $params['spuid'];
                    foreach ($params['skuList'] as $key => $item) {
                        if ($item['sku']) {
                            $branchid = isset($item['branchid']) ? $item['branchid'] : 0;
                            //第一步检查本店是否存在
                            $is_have_sku_branch = TSku::find()
                                ->where(['SKuId' => $item['sku'], 'BranchId' => $branchid])
                                ->asArray()->one();
                            $branchinfo = TBranchInfo::findOne($branchid);
                            if ($is_have_sku_branch) {
                                return json_encode(['code' => 1, 'msg' => $branchinfo['BranchName'] . '商品条码' . $item['sku'] . '已存在']);
                            }
                            //第二步检查其他商品ID下是否有这个库存
                            $is_have_sku_spu = TSku::find()
                                ->where(['SKuId' => $item['sku']])
                                ->andWhere("SpuId != '$spuid' ")
                                ->asArray()->one();
                            if ($is_have_sku_spu) {
                                return json_encode(['code' => 1, 'msg' => '其他商品下已有此库存ID' . $item['sku']]);
                            }
                            //先给各个角色的所属店铺添加库存
                            TSku::addSkuList($item, $params['spuid'], $params['workerid']);
                            //添加通用模板
                            if ($params['roles'] == 1) {
                                $branchlist = explode(',', $params['branchid']);
                                if ($branchlist['0'] == $item['branchid']) {
                                    TSku::addSku($item, $params['spuid'], $params['workerid']);
                                }
                            }
                            //商品价格
                            if (isset($item['price'])) {
                                if ($item['price']) {
                                    if (is_numeric($item['price'])) {
                                        $pattern = '/^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/';
                                        $state = preg_match($pattern, $item['price']);
                                        if (!$state) {
                                            return json_encode(['code' => 1, 'msg' => '请填写正确的价格格式']);
                                        }
                                    } else {
                                        return json_encode(['code' => 1, 'msg' => '请填写正确的价格格式']);
                                    }
                                    $spu->SpuPrice = $item['price'] * 100;
                                }
                            } else {
                                $spu->SpuPrice = 0;
                            }
                        }
                    }
                    $spu->SpuVector = json_encode($params['skuList'], JSON_UNESCAPED_UNICODE);
                } else {
                    $spu->SpuVector = json_encode([]);
                }
                $dbTrans->commit();
            } catch (Exception $e) {
                Yii::info($e,'my');
                $dbTrans->rollBack();
            }
            $spu->OnDate = date('Y-m-d H:i:s', time());
            $spu->WorkerId = $params['workerid'];
            //保存
            if ($spu->save()) {
                return 1;
            } else {
                return 2;
            }
        } catch (Exception $e){
            return json_encode(['code' => 1, 'msg' => $e]);
        }
    }

    //修改商品
    /**
     * @param $params
     * @return bool
     */
    public static function editSpu($params){
        try {
            $spu = TSpu::findOne($params['spuid']);
            $workerinfo = TWorkerInfo::find()
                ->where(['WorkerId' => $spu['WorkerId']])->asArray()->one();
            $spu->SpuName = $params['name'];
            //修改分类
            if (isset($params['category'])) {
                foreach ($params['category'] as $key => $category) {
                    if ($key == 0) {
                        $spu->CategoryId = $category['id'];
                        //商品分类属性
                        if (isset($params['tag'])) {
                            $spu->SpuAttribute = json_encode($params['tag']['selected'], JSON_UNESCAPED_UNICODE);
                        }
                    }
                    if ($key == 1) {
                        $spu->CategoryIdSub = $category['id'];
                    }
                    if ($key == 2) {
                        $spu->CategoryIdTre = $category['id'];
                    }
                }
            } else {
                $spu->CategoryId = 0;
                $spu->CategoryIdSub = 0;
                $spu->CategoryIdTre = 0;
                $spu->SpuAttribute = json_encode([]);
            }
            //启动事务
            $dbTrans = Yii::$app->db->beginTransaction();
            try {
                //库存列表修改
                if (isset($params['skuList'])) {
                    //先删除数据库多余数据(非模板数据)
                    TSku::deleteSku($params['skuList'], $params['spuid'], $params['branchid']);
                    foreach ($params['skuList'] as $key => $item) {
                        $spustr = '';
                        if ($item['sku']) {
                            $spuid = $params['spuid'];
                            //检查其他商品ID下是否有这个库存
                            $is_have_sku_spu = TSku::find()
                                ->where(['SKuId' => $item['sku']])
                                ->andWhere("SpuId != '$spuid' ")
                                ->asArray()->one();
                            if ($is_have_sku_spu) {
                                return json_encode(['code' => 1, 'msg' => '其他商品下已有此库存ID' . $item['sku']]);
                            }
                            //数据更新，新数据插入
                            $status = TSku::updateOrInsertSku($item, $params['spuid']);
                            if ($status == 'update') {
                                TSku::updateSku($item, $params['spuid'], $params['workerid']);
                            } else {
                                TSku::addSkuList($item, $params['spuid'], $params['workerid']);
                            }
                            //店长更新模板
                            if ($params['roles'] == 1 && $params['logintype'] == 2) {
                                //先删除数据库多余数据
                                $array_one = explode(',', $workerinfo['BranchIdList']);
                                $array_tow = explode(',', $params['branchid']);
                                if (array_intersect($array_one, $array_tow)) {
                                    TSku::deleteSkuAll($params['skuList'], $params['spuid']);
                                    $status = TSku::updateOrInsert($item, $params['spuid']);
                                    if ($status == 'update') {
                                        TSku::updateSkuDefalut($item, $params['spuid'], $params['workerid']);
                                    } else {
                                        TSku::addSku($item, $params['spuid'], $params['workerid']);
                                    }
                                }
                            }

                            //商品价格
                            if (isset($item['price'])) {
                                if ($item['price']) {
                                    if (is_numeric($item['price'])) {
                                        $pattern = '/^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/';
                                        $state = preg_match($pattern, $item['price']);
                                        if (!$state) {
                                            return json_encode(['code' => 1, 'msg' => '请填写正确的价格格式']);
                                        }

                                    } else {
                                        return json_encode(['code' => 1, 'msg' => '请填写正确的价格格式']);
                                    }
                                    $spu->SpuPrice = $item['price'] * 100;
                                }
                            } else {
                                $spu->SpuPrice = 0;
                            }
                        }
                        $spustr .= $item['sku'];
                    }
                    if ($spustr){
                        $spu->SpuVector = json_encode($params['skuList'], JSON_UNESCAPED_UNICODE);
                    } else{
                        $spu->SpuVector = json_encode([]);
                        TSku::deleteSkuAll($params['skuList'], $params['spuid']);
                    }
                } else {
                    $spu->SpuVector = json_encode([]);
                    TSku::delSkuList($params['spuid'], $params['branchid']);
                }
                $dbTrans->commit();
            } catch (Exception $e) {
                $dbTrans->rollBack();
            }
            $spu->OnDate = date('Y-m-d H:i:s', time());
            //$spu->WorkerId = $params['workerid'];
            //保存
            if ($spu->save()) {
                return 1;
            } else {
                return 2;
            }
        }catch (Exception $e){
            return json_encode(['code' => 1, 'msg' => $e]);
        }
    }

    public static function getSpuForUp($spuid, $branchid)
    {
        $spushop = TSpuShop::find()->where(['SpuId'=>$spuid, 'BranchId'=>$branchid])->asArray()->one();
        if(!$spushop) {
            $spushop = TSpu::find()->where(['SpuId' => $spuid])->asArray()->one();
            $category = TCategory::getCategoryName($spushop['CategoryId'],
                $spushop['CategoryIdSub'], $spushop['CategoryIdTre']);
            $spushop['category'] = $category ? $category : [];
            //商品tag标签
            $categoryattribute = json_decode($spushop['SpuAttribute'], true);
            $tag = [];
            if ($categoryattribute) {
                foreach ($categoryattribute as $key => $v) {
                    if (isset($v['name'])) {
                        $tag[$key]['name'] = $v['name'];
                    }
                    if (isset($v['tags'])) {
                        $tag[$key]['tags'] = $v['tags'];
                    }
                }
            }
            $spushop['tag'] = $tag;
            $workerinfo = TWorkerInfo::findOne($spushop['WorkerId']);
            $spushop['workername'] = $workerinfo ? $workerinfo['WorkerName'] : '';
        } else {
            $spu = TSpu::find()->where(['SpuId' => $spuid])->asArray()->one();
            $category = TCategory::getCategoryName($spu['CategoryId'],
                $spu['CategoryIdSub'], $spu['CategoryIdTre']);
            $spushop['category'] = $category ? $category : [];
            //商品tag标签
            $categoryattribute = json_decode($spu['SpuAttribute'], true);
            $tag = [];
            if ($categoryattribute) {
                foreach ($categoryattribute as $key => $v) {
                    if (isset($v['name'])) {
                        $tag[$key]['name'] = $v['name'];
                    }
                    if (isset($v['tags'])) {
                        $tag[$key]['tags'] = $v['tags'];
                    }
                }
            }
            $spushop['tag'] = $tag;
            $workerinfo = TWorkerInfo::findOne($spu['WorkerId']);
            $spushop['workername'] = $workerinfo ? $workerinfo['WorkerName'] : '';
            $spushop['SpuPrice'] = $spushop['ShowPrice'];
            $spushop['ImgUrl'] = json_decode($spushop['ImgUrl'], true);
            if ($spushop['ImgUrl']) {
                $spu_shop['ImgUrl'] = array_filter($spushop['ImgUrl']);
            }
            if ($spushop['SpuDetailType'] == 0) {
                $spushop['SpuDetail'] = json_decode($spushop['SpuDetail'], true);
            }
	    if($spushop){
                $spushop['ExpressPrice'] = $spushop['ExpressPrice'] / 100;
            }
        }
        return $spushop;
    }
    
    //模糊上架获取商品列表
    public static function getLikeSpu($keyword)
    {
        $spu = TSpu::find()->where('SpuId like :SpuId or SpuName like :SpuName ')
            ->addParams([':SpuId'=>"%$keyword%"])
            ->addParams([':SpuName'=>"%$keyword%"])
            ->limit(20)
            ->asArray()->all();
        return $spu;
    }
}
